package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.service.FileService;
import com.example.service.ImportTaskService;
import com.example.utils.download.DownloadExcelUtil;
import com.example.utils.download.DownloadTemplate;
import com.example.utils.httpServer.HttpServerUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);


    @Autowired
    private FileService fileService;

    @Autowired
    private ImportTaskService importTaskService;


    @ApiOperation(value = "导入模板下载", httpMethod = "POST")
    @RequestMapping(value = "/downloadTemplate")
    @ResponseBody
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String reqBody = HttpServerUtil.reader(request, response);
        JSONObject jsonObject = JSONObject.parseObject(reqBody);
        String language = HttpServerUtil.getValue(jsonObject,"language");
        try {
            String realPath = request.getSession().getServletContext().getRealPath("fileTemple");
            String fileName = "BareFiberAndPurchaseRecordTemplate.xlsx";
            logger.info("模板路径:" + realPath);
            String newFileName = DownloadExcelUtil.makerNewExcel(realPath, fileName);
            List<List<String>> strList = new ArrayList<>();
            DownloadExcelUtil.writeExcel(strList, newFileName);
            DownloadTemplate.downLoadFile(request, response, newFileName, language, fileName);
            logger.info("导入---下载---结束,删除文件");
            logger.info("newFileName" + newFileName);
            boolean flag = DownloadExcelUtil.deleteFile(newFileName);
            logger.info("导入---下载---结束,删除文件是否成功：" + flag);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("csyz_error", e);
            }
        }
    }
}